package com.eazy.lkv2.web.controller.activity;

import com.eazy.lkv2.web.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.UUID;

/**
 * Created by ywj on 2016/9/7.
 */
@Controller
@RequestMapping("/activity_photo")
public class ActivityPhotoUploadController extends BaseController {

    @RequestMapping(value = "activityPhotoUpload", method = {RequestMethod.POST, RequestMethod.GET})
    public void activityPhotoUpload(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException, URISyntaxException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> fileNames = multiRequest.getFileNames();
            while (fileNames.hasNext()) {
                MultipartFile file = multiRequest.getFile(fileNames.next());
                if (file != null) {
                    String fileName = file.getOriginalFilename();
                    fileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".jpg";
                    // 改写成自己的磁盘路径
                    String windows = "E:\\activity\\" + fileName;
                    String linux = "/usr/local/activity/" + fileName;
                    file.transferTo(new File(windows));
                }
            }
        }
    }
}
